In [4]:
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
In [5]:
model = BayesianModel()
In [6]:
model.add_nodes_from(["accident", "rain", "traffic_jam"])
model.add_edge("rain", "traffic_jam")
model.add_edge("accident", "traffic_jam")
In [7]:
model.nodes()
Out[7]:
In [8]:
model.edges()
Out[8]:
In [9]:
cpd_rain = TabularCPD("rain", variable_card=2, values=[[0.4, 0.6]])
cpd_accident = TabularCPD("accident", variable_card=2, values=[[0.1, 0.9]])
cpd_traffic_jam = TabularCPD(
"traffic_jam",
variable_card=2,
values=[
[0.9, 0.6, 0.7, 0.1],
[0.1, 0.4, 0.3, 0.9]
],
evidence=["rain", "accident"],
evidence_card=[2, 2])
model.add_cpds(cpd_rain, cpd_accident, cpd_traffic_jam)
model.get_cpds()
Out[9]:
In [10]:
model.check_model()
Out[10]:
In [11]:
model.get_independencies()
Out[11]:
In [12]:
model.is_active_trail("accident", "rain")
Out[12]:
In [15]:
model.is_active_trail("accident", "rain", observed="traffic_jam")
Out[15]:
Plot the network
In [44]:
import networkx as nx
import matplotlib.pyplot as plt
nx.draw(
model,
with_labels=True,
node_size=2000,
node_color="skyblue",
node_shape="o",
alpha=0.7,
linewidths=5
)
plt.show()
Now, we can run inference
In [20]:
from pgmpy.inference import VariableElimination
inference = VariableElimination(model)
# Computing the probability of bronc given smoke.
q = inference.query(variables=["traffic_jam"], evidence={"rain": 0, "accident": 1})
print(q)
In [ ]: